<script setup lang="ts">
// ----------------------- 导入相关依赖 -----------------------
import { nextTick, onMounted, onUnmounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import SysDialog from '@/components/dialog/SysDialog.vue'
import useDialog from '@/hooks/useDialog'
import useInstance from '@/hooks/useInstance'
import { MaterialListParam } from '@/api/material/type'
import { getListApi } from '@/api/material'
import { getSimpleListApi } from '@/api/materialCategory/index.ts'
import { Search, Refresh, Delete } from '@element-plus/icons-vue'
import TreeSelect from '@/components/TreeSelect/index.vue'

// ----------------------- 组件状态定义 -----------------------
const { dialog, onShow, onClose } = useDialog()
const { global } = useInstance()

// 定义emit事件
const emit = defineEmits([
  'handleMaterialSelectionChange',
  'confirmMaterialSelect',
  'handleMaterialSelect'
])

// 从已选物料中移除
const removeMaterial = (material: any, index: number) => {
  // 从已选列表中移除
  selectedMaterials.value.splice(index, 1)
  
  // 同时取消表格中的选中状态
  if (tableRef.value) {
    const tableItem = tableData.value.find((item: any) => item.id === material.id)
    if (tableItem) {
      tableRef.value.toggleRowSelection(tableItem, false)
    }
  }
  
  // 通知父组件
  emit('handleMaterialSelectionChange', selectedMaterials.value)
}

// 清空所有已选物料
const clearAllSelected = () => {
  selectedMaterials.value = []
  
  // 清空表格选中状态
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
  
  // 通知父组件
  emit('handleMaterialSelectionChange', selectedMaterials.value)
}

// 添加表格引用
const tableRef = ref()

// 表格高度自适应
const tableHeight = ref(0)

// ----------------------- 表格相关 -----------------------
const tableData = ref([])
const loading = ref(false)
const paginationData = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})

// ----------------------- 查询表单相关 -----------------------
const searchForm = reactive<MaterialListParam>({
  materialCode: undefined,
  materialName: undefined,
  categoryId: undefined,
  categoryName: undefined,  // 物料分类名称 - 用于模糊查询
  brand: undefined,
  manufacturer: undefined,
  materialType: undefined,
  materialModel: undefined,  // 添加缺少的物料型号字段
  isActive: undefined,
  page: 1,
  limit: 10,
})

// 查询方法
const search = () => {
  paginationData.currentPage = 1
  getTableData()
}

// 重置查询
const reset = () => {
  // 批量重置搜索条件，保留当前分类选择
  const currentCategoryId = searchForm.categoryId
  Object.assign(searchForm, {
    materialCode: undefined,
    materialName: undefined,
    categoryId: currentCategoryId,
    categoryName: undefined,  // 重置分类名称
    brand: undefined,
    manufacturer: undefined,
    materialModel: undefined,
    materialType: undefined,
    isActive: undefined
  })
  search()
}

// ----------------------- 表格数据处理 -----------------------
const getTableData = async () => {
  loading.value = true
  try {
    searchForm.page = paginationData.currentPage
    searchForm.limit = paginationData.pageSize
    let res = await getListApi(searchForm)
    if (res && res.data) {
      tableData.value = res.data.list
      paginationData.total = res.data.total
      
      // 等待表格数据加载完成后设置选中状态
      nextTick(() => {
        setTimeout(() => {
          if (tableRef.value && tableData.value.length > 0 && selectedMaterials.value.length > 0) {
            // 先清除选中状态
            tableRef.value.clearSelection()
            
            // 恢复选中状态
            tableData.value.forEach((row: any) => {
              const isSelected = selectedMaterials.value.some(
                (material: any) => material.id === row.id || material.materialId === row.id
              )
              console.log(`数据重置选中: ${row.materialName} - ${isSelected}`)
              if (isSelected) {
                tableRef.value.toggleRowSelection(row, true)
              }
            })
          }
        }, 100)
      })
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
  } finally {
    loading.value = false
  }
}

// ----------------------- 左侧筛选树形数据处理 -----------------------
const currentCategoryId = ref<number>()

// 保存已经选择的物料
const selectedMaterials = ref<any[]>([])

interface TreeNode {
  id: string
  categoryName: string
  parentId: string
  children: TreeNode[]
}

const treeData = ref<TreeNode[]>([])

const getTreeData = async () => {
  try {
    const res = await getSimpleListApi()
    if (res?.data) {
      treeData.value = handleTree(res.data)
    }
  } catch (error) {
    console.error('获取树形数据失败:', error)
    ElMessage.error('获取分类数据失败')
  }
}

const handleTree = (data: TreeNode[]): TreeNode[] => {
  const map = new Map<string, TreeNode>()
  const result: TreeNode[] = []

  const rootNode: TreeNode = {
    id: '-1',
    categoryName: '全部分类',
    parentId: '',
    children: [],
  }

  data.forEach((item) => {
    map.set(item.id, { ...item, children: [] })
  })

  data.forEach((item) => {
    const node = map.get(item.id)!
    if (item.parentId === '0') {
      rootNode.children.push(node)
    } else {
      const parent = map.get(item.parentId)
      if (parent) {
        parent.children.push(node)
      }
    }
  })

  result.push(rootNode)
  return result
}

const handleTreeNodeClick = async (data: any) => {
  if (data.id === '-1') {
    currentCategoryId.value = undefined
    searchForm.categoryId = undefined
  } else {
    currentCategoryId.value = data.id
    searchForm.categoryId = data.id
  }
  searchForm.page = 1
  searchForm.limit = 10
  searchForm.materialCode = undefined
  searchForm.materialName = undefined
  searchForm.brand = undefined
  searchForm.manufacturer = undefined
  searchForm.materialModel = undefined  // 重置物料型号字段
  await getTableData()
}

// 选择物料 selection：全部选中的数据     当前点击数据row
const handleSelect = (selection: any[], row: any) => {
  console.log("组件选择物料数据：", selection, "当前行:", row);
  
  // 判断是选中还是取消
  const isSelected = selection.some(item => item.id === row.id)
  
  if (isSelected) {
    // 勾选了则添加到已选数组中（如果不存在的话）
    const exists = selectedMaterials.value.some(item => item.id === row.id)
    if (!exists) {
      selectedMaterials.value.push(row)
    }
  } else {
    // 取消选中则从已选数组中移除
    selectedMaterials.value = selectedMaterials.value.filter(item => item.id !== row.id)
  }
  
  console.log("是否选择：", isSelected);
  console.log("已选数据数量：", selectedMaterials.value.length);
  console.log("已选材料：", selectedMaterials.value.map(m => m.materialName));
  
  emit('handleMaterialSelectionChange', selectedMaterials.value)
}

// 全选
const handleSelectAll = (selection: any[]) => {
  console.log("全选操作：", selection.length, "当前页数据：", tableData.value.length)
  
  // 判断是全选还是取消全选
  const isSelected = selection.length === tableData.value.length
  
  if (isSelected) {
    // 全选：将当前页面的所有数据添加到已选数组中（去重）
    selection.forEach(item => {
      const exists = selectedMaterials.value.some((row: any) => row.id === item.id)
      if (!exists) {
        selectedMaterials.value.push(item)
      }
    })
  } else {
    // 取消全选：清空当前tableData中的已选数据
    selectedMaterials.value = selectedMaterials.value.filter((item: any) => {
      return !tableData.value.some((row: any) => row.id === item.id)
    })
  }
  
  console.log("全选后已选数据数量：", selectedMaterials.value.length)
  emit('handleMaterialSelectionChange', selectedMaterials.value)
}

// 确认选择完毕
const confirmMaterial = () => {
  emit('confirmMaterialSelect')
}

// 关闭弹框
const closeDialog = () => {
  // 清理状态
  selectedMaterials.value = []
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
  onClose()
}

// ----------------------- 生命周期钩子 -----------------------
onMounted(() => {
  dialog.height = 700
  dialog.width = 1400
  dialog.title = '选择物料'
  getTreeData()
  getTableData()
  nextTick(() => {
    tableHeight.value = 480
  })
})

// 监听窗口大小变化
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = 480
  })
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 暴露方法给父组件
defineExpose({
  onShow: (preSelectedMaterials = []) => {
    console.log("本次预选的数据:", preSelectedMaterials);
    dialog.visible = true
    
    // 完全重置已选物料状态
    selectedMaterials.value = [...(preSelectedMaterials || [])]
    
    // 重新加载表格数据并设置选中状态
    nextTick(async () => {
      await getTableData()
      
      // 等待表格渲染完成后设置选中状态
      setTimeout(() => {
        if (tableRef.value && tableData.value.length > 0) {
          // 先清除所有选中状态
          tableRef.value.clearSelection()
          
          // 设置选中状态
          if (preSelectedMaterials && preSelectedMaterials.length > 0) {
            tableData.value.forEach((row: any) => {
              const isSelected = preSelectedMaterials.some(
                (material: any) => material.id === row.id || material.materialId === row.id
              )
              console.log(`物料 ${row.materialName} 是否预选:`, isSelected)
              if (isSelected) {
                tableRef.value.toggleRowSelection(row, true)
              }
            })
          }
        }
      }, 500)
    })
  },
  onClose: () => {
    // 关闭时清理状态
    selectedMaterials.value = []
    if (tableRef.value) {
      tableRef.value.clearSelection()
    }
    onClose()
  },
})

// 接收父组件参数
const props = defineProps({
  multiple: {
    type: Boolean,
    default: true
  }
})

// 点击选择某一行，获取那行的数据
const handleRowClick = (row: any) => {
  if (!props.multiple) {
    emit('handleMaterialSelect', row)
    console.log("物料子传父："+row.materialName)
    closeDialog()
  }
}
</script>

<template>
  <sys-dialog :title="dialog.title"
              :width="dialog.width"
              :visible="dialog.visible"
              :height="dialog.height"
              @onClose="closeDialog"
              @on-confirm="confirmMaterial">
    <template #content>
      <div class="material-dialog-container">
        <el-row :gutter="10">
          <!-- 左侧树形菜单 -->
          <el-col :span="4">
            <div class="tree-container">
              <TreeSelect :data="treeData"
                          :props="{
                    children: 'children',
                    label: 'categoryName'
                  }"
                          placeholder="请输入分类名称"
                          @node-click="handleTreeNodeClick" />
            </div>
          </el-col>
          <!-- 中间内容区 -->
          <el-col :span="15">
            <!-- 查询表单区域 -->
            <el-card class="search-card" shadow="hover">
              <el-form :inline="true"
                       :model="searchForm"
                       class="search-form">
                <el-form-item label="物料编码">
                  <el-input v-model="searchForm.materialCode"
                            placeholder="请输入物料编码" 
                            clearable 
                            prefix-icon="Document" />
                </el-form-item>
                <el-form-item label="物料名称">
                  <el-input v-model="searchForm.materialName"
                            placeholder="请输入物料名称" 
                            clearable 
                            prefix-icon="Goods" />
                </el-form-item>
                <el-form-item label="物料分类">
                  <el-input v-model="searchForm.categoryName"
                            placeholder="请输入分类名称" 
                            clearable 
                            prefix-icon="Folder" />
                </el-form-item>
                <el-form-item label="物料型号">
                  <el-input v-model="searchForm.materialModel"
                            placeholder="请输入物料型号" 
                            clearable 
                            prefix-icon="Grid" />
                </el-form-item>
                <el-form-item label="材质">
                  <el-input v-model="searchForm.materialType"
                            placeholder="请输入材质" 
                            clearable 
                            prefix-icon="Setting" />
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="searchForm.isActive"
                            placeholder="请选择状态" 
                            clearable
                            style="width: 120px">
                    <el-option label="启用" :value="0" />
                    <el-option label="禁用" :value="1" />
                  </el-select>
                </el-form-item>
                <el-form-item class="search-buttons">
                  <el-button type="primary"
                             @click="search"
                             class="search-btn"
                             :icon="Search">
                    查询
                  </el-button>
                  <el-button @click="reset"
                             class="reset-btn"
                             :icon="Refresh">
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>

            <!-- 表格区域 -->
            <div class="table-scroll-container" style="margin-top: 15px;">
              <el-table v-loading="loading"
                        :data="tableData"
                        border
                        :height="tableHeight"
                        @select="handleSelect"
                        @select-all="handleSelectAll"
                        @row-click="handleRowClick"
                        ref="tableRef">
              <el-table-column v-if="multiple" type="selection" width="55" />
              <el-table-column prop="materialCode"
                               label="物料编码"
                               min-width="120"
                               show-overflow-tooltip />
              <el-table-column prop="materialName"
                               label="物料名称"
                               min-width="150"
                               show-overflow-tooltip />
              <el-table-column prop="categoryName"
                               label="物料类型"
                               min-width="120"
                               show-overflow-tooltip />
              <el-table-column prop="unitName"
                               label="计量单位"
                               min-width="90"
                               show-overflow-tooltip />
              <el-table-column prop="specification"
                               label="规格"
                               min-width="150"
                               show-overflow-tooltip />
              <el-table-column prop="materialModel"
                               label="型号"
                               min-width="120"
                               show-overflow-tooltip />
              <el-table-column prop="materialType" 
                               label="材质" 
                               min-width="80"
                               show-overflow-tooltip />
              <el-table-column prop="purchasePrice"
                               label="采购单价"
                               min-width="90"
                               show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.purchasePrice">¥{{ scope.row.purchasePrice }}</span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="price"
                               label="采购价格"
                               min-width="90"
                               show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.price">¥{{ scope.row.price }}</span>
                  <span v-else>-</span>
                </template>
              </el-table-column>

              <el-table-column prop="unitWeight" 
                               label="单重" 
                               min-width="80"
                               show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.unitWeight">{{ scope.row.unitWeight }}</span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              </el-table>
            </div>

            <!-- 分页 -->
            <el-pagination v-model:current-page="paginationData.currentPage"
                           v-model:page-size="paginationData.pageSize"
                           :page-sizes="[10, 20, 50]"
                           :total="paginationData.total"
                           layout="total, sizes, prev, pager, next"
                           class="pagination"
                           @size-change="getTableData"
                           @current-change="getTableData" />
          </el-col>
          <!-- 右侧已选物料区 -->
          <el-col :span="5" class="selected-col">
            <div class="selected-materials">
              <div class="selected-header">
                <span>已选物料</span>
                <el-badge :value="selectedMaterials.length" class="item" type="primary" />
              </div>
              <div class="selected-list">
                <div v-if="selectedMaterials.length === 0" class="empty-selected">
                  <el-empty description="暂无选中物料" :image-size="60" />
                </div>
                <div v-else>
                  <div 
                    v-for="(material, index) in selectedMaterials" 
                    :key="material.id"
                    class="selected-item"
                  >
                    <div class="item-content">
                      <div class="item-name" :title="material.materialName">{{ material.materialName }}</div>
                      <div class="item-spec" :title="material.specification">{{ material.specification || '无规格' }}</div>
                      <div class="item-price">¥{{ material.price ? material.price.toFixed(2) : '0.00' }}</div>
                    </div>
                    <el-button 
                      type="danger" 
                      size="small" 
                      :icon="Delete" 
                      circle
                      @click="removeMaterial(material, index)"
                      class="remove-btn"
                    />
                  </div>
                </div>
              </div>
              <div class="selected-footer" v-if="selectedMaterials.length > 0">
                <el-button type="warning" size="small" @click="clearAllSelected">
                  清空全部
                </el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </template>
  </sys-dialog>
</template>

<style scoped lang="scss">
.material-dialog-container {
  padding: 0 0px;
  box-sizing: border-box;
  height: 100%;
  overflow: hidden;
}

.el-pagination {
  margin-top: 10px;
  justify-content: flex-end;
}

.search-card {
  height: 65px;

  :deep(.el-card__body) {
    padding: 10px;
  }
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 10px;
  margin-bottom: 0;
}

:deep(.el-input) {
  width: 180px;
}

.search-buttons {
  .search-btn,
  .reset-btn {
    margin-left: 5px;
  }
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 8px;
  margin-bottom: 0;
}

:deep(.el-input) {
  width: 160px;
}

.table-scroll-container {
  overflow-x: auto;
  overflow-y: hidden;
}

.tree-container {
  height: 600px;
  
  // 覆盖TreeSelect组件的样式，确保能够滚动
  :deep(.tree-select-card) {
    height: 100%;
    border: 1px solid #dcdfe6;
    
    .el-card__body {
      height: 100%;
      display: flex;
      flex-direction: column;
      padding: 12px;
    }
    
    // 强制显示滚动条，覆盖原有的hover样式
    .mt-2 {
      flex: 1;
      overflow-y: auto !important;
      overflow-x: hidden;
      max-height: calc(100% - 50px); // 减去搜索框的高度
      
      // 自定义滚动条样式
      &::-webkit-scrollbar {
        width: 6px;
      }

      &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
      }

      &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 3px;
        
        &:hover {
          background: #a8a8a8;
        }
      }
    }
  }
}

.selected-col {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.selected-materials {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fff;
  min-height: 600px;
  max-height: 600px;
  display: flex;
  flex-direction: column;

  .selected-header {
    padding: 12px 16px;
    border-bottom: 1px solid #ebeef5;
    background: #f5f7fa;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-weight: 600;
    font-size: 14px;
    color: #303133;

    .el-badge {
      :deep(.el-badge__content) {
        background-color: #409eff;
      }
    }
  }

  .selected-list {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 8px;
    max-height: calc(100% - 120px);

    // 自定义滚动条样式
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 3px;
      
      &:hover {
        background: #a8a8a8;
      }
    }

    .empty-selected {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .selected-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 8px 12px;
      margin-bottom: 8px;
      background: #f9f9f9;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      transition: all 0.3s;
      
      &:hover {
        background: #ecf5ff;
        border-color: #b3d8ff;
      }

      .item-content {
        flex: 1;
        min-width: 0;

        .item-name {
          font-size: 13px;
          font-weight: 600;
          color: #303133;
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .item-spec {
          font-size: 12px;
          color: #909399;
          margin-bottom: 2px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .item-price {
          font-size: 12px;
          font-weight: 600;
          color: #f56c6c;
        }
      }

      .remove-btn {
        margin-left: 8px;
        width: 24px;
        height: 24px;
        
        :deep(.el-icon) {
          font-size: 12px;
        }
      }
    }
  }

  .selected-footer {
    padding: 12px 16px;
    border-top: 1px solid #ebeef5;
    background: #f5f7fa;
    text-align: center;
  }
}
</style>
